package com.huabo.contract.controller;


import com.alibaba.fastjson.JSONObject;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblAttachment;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.FtpUtil;
import com.hbfk.util.JsonBean;
import com.huabo.contract.oracle.entity.TblContractAppendixsigning;
import com.huabo.contract.oracle.entity.TblContractPlannode;
import com.huabo.contract.oracle.entity.TblContractSpnode;
import com.huabo.contract.oracle.entity.TblCyhwUnit;
import com.huabo.contract.service.TblContractAppendixsigningService;
import com.huabo.contract.service.TblContractPlannodeService;
import com.huabo.contract.service.TblContractSpnodeService;
import com.huabo.contract.service.TblCyhwUnitService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

@RestController
@Slf4j
@Api(value="合同履行Controller",tags={"合同履行所有接口"})
public class ContractPerformanceController {
	private static final Log logger = LogFactory.getLog(ContractPerformanceController.class);
	@Resource
	private TblCyhwUnitService tblCyhwUnitService;
	@Resource
	private TblContractPlannodeService tblContractPlannodeService;
	@Resource
	private TblContractSpnodeService tblContractSpnodeService;
	@Resource
	private TblContractAppendixsigningService tblContractAppendixsigningService;

	/**
	 *我的合同-列表
	 * @param request
	 * @param unit
	 * @param flowId
	 * @param pageNumber
	 * @param pageSize
	 * @param token
	 * @param staffId
	 * @return
	 */

	@RequestMapping(value = "/contract/mineContract",method = {RequestMethod.POST} ,produces = "application/html; charset=utf-8")
	@ApiOperation(value="我的合同-列表")
	public String mineContract(HttpServletRequest request,TblCyhwUnit unit,
									 @ApiParam(name="flowId",value="流程Id主键",required=true)String flowId,
									 @ApiParam(name="pageNumber",value="当前页",required=false,defaultValue = "1")Integer pageNumber,
									 @ApiParam(name="pageSize",value="每页数量",required=false,defaultValue = "10")Integer pageSize,
									 @ApiParam(name="token",value="登录用户token",required=true) @RequestHeader("token") String token,
									 @ApiParam(name="staffId",value="用户Id主键",required=false)String staffId){
		String result = null;
		try {
			Map<String, Object> resultMap = this.tblCyhwUnitService.findeContractListByContractStaff(flowId,pageNumber,pageSize,token, staffId,unit);
			JSONObject jsonObj = new JSONObject(resultMap);
			result = jsonObj.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 *履行跟踪-列表
	 * @param request
	 * @param unit
	 * @param flowId
	 * @param pageNumber
	 * @param pageSize
	 * @param token
	 * @param staffId
	 * @return
	 */
	@RequestMapping(value = "/contract/performanceTracking",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
	@ApiOperation(value="履行跟踪-列表")
	public String contract_performanceTrackingt(HttpServletRequest request,TblCyhwUnit unit,
													  @ApiParam(name="flowId",value="流程Id主键",required=true)String flowId,
													  @ApiParam(name="pageNumber",value="当前页",required=false,defaultValue = "1")Integer pageNumber,
													  @ApiParam(name="pageSize",value="每页数量",required=false,defaultValue = "10")Integer pageSize,
													  @ApiParam(name="token",value="登录用户token",required=true) @RequestHeader("token") String token,
													  @ApiParam(name="staffId",value="用户Id主键",required=false)String staffId){

		String result = null;
		try {
			Map<String, Object> resultMap = this.tblCyhwUnitService.findeContractListPerformanceTracking(flowId,pageNumber,pageSize,token, staffId,unit);
			JSONObject jsonObj = new JSONObject(resultMap);
			result = jsonObj.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**履行落实-列表
	 *
	 * @param response
	 * @param request
	 * @param unit
	 * @param flowId
	 * @param pageNumber
	 * @param pageSize
	 * @param token
	 * @param staffId
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value = "/contract/fulfillment",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
	@ApiOperation(value="履行落实-列表")
	public String contract_fulfillment(HttpServletResponse response, HttpServletRequest request,TblCyhwUnit unit,
									   @ApiParam(name="flowId",value="流程Id主键",required=true)String flowId,
									   @ApiParam(name="pageNumber",value="当前页",required=false,defaultValue = "1")Integer pageNumber,
									   @ApiParam(name="pageSize",value="每页数量",required=false,defaultValue = "10")Integer pageSize,
									   @ApiParam(name="token",value="登录用户token",required=true) @RequestHeader("token") String token,
									   @ApiParam(name="staffId",value="用户Id主键",required=false)String staffId)throws Exception{
		String result = null;
		try {
			Map<String, Object> resultMap = this.tblCyhwUnitService.findFulfillmentContract(flowId,pageNumber,pageSize,token, staffId,unit);
			JSONObject jsonObj = new JSONObject(resultMap);
			result = jsonObj.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 我的合同-执行
	 * @param request
	 * @param contractId
	 * @return
	 */
	@RequestMapping(value = "/contract/excuteContractId",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
	@ApiOperation(value="我的合同-执行")
	@ResponseBody
	public String contract_excuteContractId(HttpServletRequest request,
											@RequestParam(value="contractId",required=true)String contractId){

		String result = null;
		try {
			Map<String, Object> resultMap = this.tblCyhwUnitService.contractExcuteContractId(contractId,"7");
			JSONObject jsonObj = new JSONObject(resultMap);
			result = jsonObj.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 我的合同-比对前置页面
	 * @param request
	 * @param contractId
	 * @return
	 */
	@RequestMapping(value = "/contractManagement/documentComparison",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
	@ApiOperation(value="我的合同-比对前置页面")
	public String contractManagement_documentComparison(HttpServletRequest request,
														@ApiParam(value="contractId",required=true)String contractId){
		String result = null;
		try {
			Map<String, Object> resultMap = this.tblCyhwUnitService.findContractDes(contractId);
			JSONObject jsonObj = new JSONObject(resultMap);
			result = jsonObj.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

//	@RequestMapping(value = "/contract/doDiff",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
//	@ApiOperation(value="我的合同-比对")
//	@ResponseBody
//	public String doDiff(HttpServletRequest request,String content1,String content2) {
//		String resultJson = null;
//		try {
//			Map<String,Object> resultMap = new HashMap<String,Object>(0);
//			DocumentCompare dc=new DocumentCompare();
//			//String path = request.getSession().getServletContext().getRealPath("/WEB-INF/doc/");
//			String path = System.getProperty("user.dir");
//
//			dc.createWord(path,"test1.doc");
//			dc.createWord(path,"test2.doc");
//			dc.writeDataDocx(path+"/test1.doc", content1, true, 12);
//			dc.writeDataDocx(path+"/test2.doc", content2, true, 12);
//			String url =  "https://doc-compare.intsig.com/doc_compare/create";
//			String appKey = "5e53ae213d99c3f05f8f802f4cec7e6d"; // your app_key
//			String appSecret = "7e2500d9207f447a5ccc25233 62d7340"; // your app_secret
//			BufferedReader in = null;
//			OutputStream out = null;
//			String result = "";
//			StringBuffer sbf = new StringBuffer();
//			try {
//				// byte[] imgData = readfile("D:\\360安全浏览器下载\\1_北京历史文化名城保护条例.docx"); // image
//				BestSignClient sing=new BestSignClient();
//				URL realUrl = new URL(url);
//				HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
//				conn.setRequestProperty("connection", "Keep-Alive");
//				conn.setRequestProperty("Content-Type", "application/json");
//				conn.setRequestProperty("app-key",appKey);
//				conn.setRequestProperty("app-secret",appSecret);
//				conn.setDoOutput(true);
//				conn.setDoInput(true);
//				conn.setRequestMethod("POST"); // 设置请求方式
//				JSONObject obj=new JSONObject();
//				obj.put("convert_arg", JSONObject.parse("{'remove_stamp':'1','remove_comments':'0','remove_footnote':'0','remove_headerfooter':'0'}"));
//				obj.put("standard_doc", JSONArray.parse("[{'filedata':'"+sing.encodeBase64File(path+"/test1.doc")+"','filename':'test1.doc'}]"));
//				obj.put("compare_doc",JSONArray.parse("[{'filedata':'"+sing.encodeBase64File(path+"/test2.doc")+"','filename':'test2.doc'}]"));
//				out = conn.getOutputStream();//向对象输出流写出数据，这些数据将存到内存缓冲区中
//				out.write(obj.toString().getBytes());            //out.write(new String("测试数据").getBytes());            //刷新对象输出流，将任何字节都写入潜在的流中
//				out.flush();
//				// 关闭流对象,此时，不能再向对象输出流写入任何数据，先前写入的数据存在于内存缓冲区中
//				out.close();
//				InputStream is = conn.getInputStream();
//				in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//				String strRead = null;
//				while ((strRead = in.readLine()) != null) {
//					sbf.append(strRead);
//					sbf.append("\r\n");
//				}
//				in.close();
//				resultMap.put("url", JSONObject.parseObject(sbf.toString()).getString("url"));
//				resultMap.put("code",JSONObject.parseObject(sbf.toString()).getString("code"));
//			} catch (Exception e) {
//				System.out.println("发送 POST 请求出现异常！" + e);
//				e.printStackTrace();
//			}
//			finally {
//				try {
//					if (out != null) {
//						out.close();
//					}
//					if (in != null) {
//						in.close();
//					}
//				} catch (IOException ex) {
//					ex.printStackTrace();
//				}
//			}
//			resultJson = JSONObject.toJSONString(resultMap);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return resultJson;
//	}

	/**
	 *履行跟踪-跟踪
	 * @param model
	 * @param response
	 * @param request
	 * @param contractId
	 * @param pageNumber
	 * @param pageSize
	 * @param token
	 * @param staffId
	 * @param node
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value = "/contract/contractTracking",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
	@ApiOperation(value="履行跟踪-跟踪/履行落实-落实")
	public String contract_contractTracking(Model model,HttpServletResponse response,HttpServletRequest request,
											@ApiParam(value="contractId",required=false)Integer contractId,
											@ApiParam(name="pageNumber",value="当前页",required=false,defaultValue = "1")Integer pageNumber,
											@ApiParam(name="pageSize",value="每页数量",required=false,defaultValue = "10")Integer pageSize,
											@ApiParam(name="token",value="登录用户token",required=true) @RequestHeader("token") String token,
											@ApiParam(name="staffId",value="用户Id主键",required=false)String staffId,
											TblContractPlannode node)throws Exception{

		String result = null;
		try {
			Map<String, Object> resultMap = this.tblContractPlannodeService.findWorkableContractNodeByPageInfo(contractId,pageNumber,pageSize,token,node);
			JSONObject jsonObj = new JSONObject(resultMap);
			result = jsonObj.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 *履行跟踪-跟踪审批回显
	 * @param planId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/contract/approvalContractPlanNode",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
	@ApiOperation(value="履行跟踪-跟踪审批回显")
	public String contract_approvalContractPlanNode(
													@ApiParam(value="planId",required=true)Integer planId)throws Exception{
		String result = null;
		Map<String,Object> resultMap = new HashMap<String, Object>(0);
		Map<String,Object> dataMap = new HashMap<String, Object>(0);
		TblContractPlannode node = this.tblContractPlannodeService.findWriteContractPlanNode(planId);
		List<TblAttachment> attList = this.tblContractPlannodeService.findeWriteContractPlanFileInfo(planId);
		dataMap.put("node",node);
		dataMap.put("attList",attList);
		resultMap.put("code", "1");
		resultMap.put("msg", "成功！");
		resultMap.put("data",dataMap);
		JSONObject jsonObj = new JSONObject(resultMap);
		result = jsonObj.toString();
		return result;
	}

	/**
	 * 履行跟踪-审批——通过/驳回  履行落实-提交
	 * @param nodeId
	 * @param response
	 * @param request
	 * @param planStatus
	 * @param feedback
	 * @return
	 */
	@RequestMapping(value = "/contract/modifyContractNodeStatus",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
	@ApiOperation(value="履行跟踪-审批——通过/驳回")
	@ResponseBody
	public String downloadFtp_modifyContractNodeStatus(@ApiParam(value="nodeId",required=true)Integer nodeId, HttpServletResponse response,HttpServletRequest request,
													 @ApiParam(value="planStatus",required=true)Integer planStatus,
													 @ApiParam(value="feedback",required=true,defaultValue = "")String feedback) {

		String result = null;
		try {
			Map<String, Object> resultMap = this.tblContractPlannodeService.modifyPlanNodeStatus(nodeId,planStatus,feedback);
			JSONObject jsonObj = new JSONObject(resultMap);
			result = jsonObj.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


	/**履行落实-落实保存
	 *
	 * @param spNode
	 * @param nodeId
	 * @param contractId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/contract/modifyContractSpNodeInfo",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
	@ApiOperation(value="履行落实-落实保存")
	@ResponseBody
	public String contract_modifyContractSpNodeInfo(TblContractSpnode spNode,
													 @ApiParam(value="nodeId",required=true)Integer nodeId,
													 @ApiParam(value="contractId",required=true)Integer contractId)throws Exception{

		String result = null;
		try {
			Map<String, Object> resultMap = this.tblContractSpnodeService.saveOrUpdateContractSpnode(spNode,nodeId,contractId);
			JSONObject jsonObj = new JSONObject(resultMap);
			result = jsonObj.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**我的合同-合同暂停/变更/终止
	 *
	 * @param request
	 * @param contractId
	 * @param goalStatus
	 * @return
	 */
	@RequestMapping(value = "/contract/changeContractStatus",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
	@ApiOperation(value="我的合同-合同暂停/变更/终止")
	@ResponseBody
	public String contract_changeContractStatus(HttpServletRequest request,
												@RequestParam(value="contractId",required=true)String contractId,
												@RequestParam(value="goalStatus",required=true)Integer goalStatus){

		String result = null;
		try {
			Map<String, Object> resultMap = this.tblCyhwUnitService.modifyContractStatus(contractId,goalStatus);
			JSONObject jsonObj = new JSONObject(resultMap);
			result = jsonObj.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 我的合同-附件删除列表
	 * @param contractId
	 * @param pageNumber
	 * @param pageSize
	 * @param tca
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/contract/showSealFileList",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
	@ApiOperation(value="我的合同-附件删除列表")
	public String contract_showSealFileList(@ApiParam(value="contractId",required=false)Integer contractId,
											@ApiParam(name="pageNumber",value="当前页",required=false,defaultValue = "1")Integer pageNumber,
											@ApiParam(name="pageSize",value="每页数量",required=false,defaultValue = "10")Integer pageSize,
											TblContractAppendixsigning tca)throws Exception{

		String result = null;
		try {
			Map<String, Object> resultMap = this.tblContractAppendixsigningService.findFileListByContractIdPageInfo(contractId,pageNumber,pageSize,tca);
			JSONObject jsonObj = new JSONObject(resultMap);
			result = jsonObj.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 我的合同-附件删除
	 * @param singingId
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "/contract/deleteFile",method = {RequestMethod.POST},produces = "application/html; charset=utf-8")
	@ApiOperation(value="我的合同-附件删除")
	public String deleteFile(@RequestParam(value="singingId",required=true)Integer singingId,
						   HttpServletResponse response,HttpServletRequest request) {
		try {
			boolean bool = false;
			TblContractAppendixsigning signing = this.tblContractAppendixsigningService.findInfoById(singingId);
			/*String path = request.getSession().getServletContext().getRealPath("/WEB-INF/js/pdfview/web");
			String pdfname = signing.getSingingPath().substring(0,signing.getSingingPath().indexOf(".")-1)+".pdf";
			String pdfpath = path+"/"+pdfname;*/
			if (signing != null) {
				bool = FtpUtil.removeFile(signing.getSingingPath(), FtpUtil.constractfilepath);
				/*File pdffile = new File(pdfpath);
				pdffile.delete();
				pdffile = new File(path+signing.getSingingPath());
				pdffile.delete();*/
				this.tblContractAppendixsigningService.removeInfo(singingId);
			} else {
				logger.info("附件不存在");
			}
			if (bool) {
				logger.info("删除成功");
			} else {
				logger.info("删除失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JsonBean.success();
	}

	/**
	 * 我的合同-附件上传
	 * @param file
	 * @param contractId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/contract/importFile",method=RequestMethod.POST,produces = "application/html; charset=utf-8")
	@ResponseBody
	public String importRiskClassExcel(@ApiParam(name="file",value="file",required=true)MultipartFile file,
										@ApiParam(value="contractId",required=true)Integer contractId,
										@ApiParam(name="token",value="登录用户token",required=true) @RequestHeader("token") String token) throws Exception {
		String result = null;
		TblStaffUtil user = DealUserToken.parseUserToken(token);
		String fileName = file.getOriginalFilename();
		long timeInMillis = Calendar.getInstance().getTimeInMillis();
		String oldname = fileName.substring(0,fileName.lastIndexOf("."));
		String newname=fileName.replace(oldname,""+timeInMillis);
		long size = file.getSize()/1024;
		try {
			boolean flag = FtpUtil.constractUploadFile(newname, file.getInputStream());
			if(flag){
				logger.info("上传成功");
			}else{
				logger.info("上传失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		TblContractAppendixsigning signing = new TblContractAppendixsigning();
		signing.setConstractId(new BigDecimal(contractId));
		signing.setSingingName(fileName);
		signing.setSingingSize(new BigDecimal(size));
		signing.setSingingType(0);
		signing.setSingingStatus(0);
		signing.setSingingPath(newname);
		signing.setUploader(user.getStaffid().intValue());
		signing.setUploadTime(new Date());
		Map<String,Object> resultMap = this.tblContractAppendixsigningService.saveEntity(signing);
		JSONObject jsonObj = new JSONObject(resultMap);
		result = jsonObj.toString();
		return result;
	}

	/**
	 * 我的合同-附件下载
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/downloadFtp/upload",method=RequestMethod.GET,produces = "application/html; charset=utf-8")
	@ApiOperation(value="签署文件下载")
	public void downloadFtp(@RequestParam(value="singingId",required=true)Integer singingId, HttpServletResponse response,HttpServletRequest request) {
		try {
			boolean bool = false;
			TblContractAppendixsigning signing = this.tblContractAppendixsigningService.findInfoById(singingId);
			if (signing != null) {
				com.hbfk.entity.TblContractAppendixsigning sing = new com.hbfk.entity.TblContractAppendixsigning();
				sing.setSingingId(singingId);
				sing.setSingingName(signing.getSingingName());
				sing.setSingingPath(signing.getSingingPath());
				FtpUtil.downloadConstractFile(sing, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



























}
